package qiniu

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"gvb_server/config"
	"gvb_server/global"
	"time"
)

type MyPutRet struct {
	Key    string
	Hash   string
	Fsize  int
	Bucket string
	Name   string
}

// 获取token
func getToken(q config.QiNiu) string {
	accessKey := q.AccessKey
	secretKey := q.SecretKey
	bucket := q.Bucket
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	mac := qbox.NewMac(accessKey, secretKey)
	uploadToken := putPolicy.UploadToken(mac)
	return uploadToken
}

// 获取配置
func getCfg(q config.QiNiu) storage.Config {
	cfg := storage.Config{}
	// 空间对应的机房
	zone, _ := storage.GetRegionByID(storage.RegionID(q.Zone))
	cfg.Zone = &zone
	// 是否使用https
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	return cfg
}

// UploadImage 上传图片
func UploadImage(data []byte, prefix string) (filePath string, err error) {
	q := global.Config.QiNiu
	if q.AccessKey == "" || q.SecretKey == "" {
		return "", errors.New("请配置AccessKey和SecretKey")
	}
	fileSize := float64(len(data) / 1024 / 1024)
	if fileSize > q.Size {
		return "", errors.New(fmt.Sprintf("文件超过设置的大小，当前文件大小为: %.2f, 支持的最大文件大小为：%.2f", fileSize, q.Size))
	}
	token := getToken(q)
	cfg := getCfg(q)
	ret := MyPutRet{}
	putExtra := storage.PutExtra{}
	formUploader := storage.NewFormUploader(&cfg)
	now := time.Now().Format("20060102150405")
	key := fmt.Sprintf("%s-%s", prefix, now)
	err = formUploader.Put(context.Background(), &ret, token, key, bytes.NewReader(data), int64(len(data)), &putExtra)
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%s/%s", global.Config.QiNiu.CDN, key), nil
}
